<template>
  <page-layout title="角色管理">
    <div class="role-management">
      <a-row type="flex" justify="center" align="middle">
        <a-col :span="8">
          <a-form layout="inline">
            <a-form-item>
              <a-input v-model="params.roleName" placeholder="请输入角色名称" allow-clear>
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="onSearch">
                <a-icon type="search" />查询
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" :offset="10" style="text-align:right;">
          <a-button type="primary" @click="onNewRole">
            <a-icon type="plus" />添加角色
          </a-button>
        </a-col>
      </a-row>
      <a-table class="roles-table" rowKey="id" :columns="columns" :data-source="dataSource" :pagination="{
      current: params.page,
      pageSize: params.pageSize,
      total: total,
      showLessItems: true,
      onChange: onPageChange,
      onShowSizeChange: onSizeChange,
    }">>
        <template v-for="col in ['name','enableIf', 'memo', 'updateTime']" :slot="col" slot-scope="text, record">
          <div :key="col">
            <a-input v-if="record.editable&&col != 'enableIf'" style="margin: -5px 0" :value="text" @change="e => handleChange(e.target.value, record.id, col)" />
            <a-switch v-if="record.editable&&col == 'enableIf'" v-model="record.enableIf" checked-children="启用" un-checked-children="禁用" />
            <template :disabled="editingKey !== ''" v-else>
              <span v-if="col == 'enableIf' ">
                <a-badge v-if="record.enableIf" color="green" text="启用" />
                <a-badge v-else color="red" text="禁用" />
              </span>
              <span v-else>{{text}}</span>
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-space v-if="record.editable" :size="size">
            <a @click="() => save(record.id)">保存</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要取消保存吗?" @confirm="cancel(record.id)">
              <a>取消</a>
            </a-popconfirm>
          </a-space>
          <a-space v-else :size="size">
            <a class="ant-dropdown-link" @click="onDetail(record)">详情</a>
            <a-divider type="vertical" v-if="record.enableIf" />
            <a class="ant-dropdown-link" :disabled="editingKey !== ''" @click="edit(record.id)">{{record.enableIf?'编辑':''}}</a>
            <a-divider type="vertical" v-if="record.enableIf" />
            <a class="ant-dropdown-link" v-if="record.enableIf" @click="onAdd(record)">添加人员</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除该角色吗?" ok-text="确定" cancel-text="取消" @confirm="onConfirmDelete()">
              <a class="ant-dropdown-link" @click="onDelete(record.id)">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
      <!-- 新建角色Modal -->
      <editRole :isRoleModal="isRoleModal" @cancelModal="onCancel"></editRole>
      <!-- 添加成员Modal -->
      <addMember :memberModal="isMemberModal" @cancelModal="onCancel" :roleName="nowRoleName"></addMember>
    </div>
  </page-layout>
</template>

<script>
import PageLayout from "@/layouts/PageLayout";
import editRole from "@/pages/owns/EditRoleModal";
import addMember from "@/pages/owns/addMemberModal";
import { roleList, updateRole, deleteRole, addMemeber } from '@/services/role'
import { transferDate } from '@/utils/util';
export default {
  name: "roleManagement",
  components: { editRole, addMember, PageLayout },
  data () {
    return {
      params: {
        roleName: "",
        page: 1,
        pageSize: 10,
      },
      total: 0,
      columns: [
        {
          title: "角色名称",
          dataIndex: "name",
          width: "12%",
          scopedSlots: { customRender: "name" }
        },
        {
          title: "状态",
          dataIndex: "enableIf",
          width: "10%",
          scopedSlots: { customRender: "enableIf" }
        },
        {
          title: "角色描述",
          dataIndex: "memo",
          width: "35%",
          scopedSlots: { customRender: "memo" }
        },
        {
          title: "更新时间",
          dataIndex: "updateTime",
          width: "15%",
          scopedSlots: { customRender: "updateTime" }
        },
        {
          title: "操作",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" }
        }
      ],
      dataSource: [],
      editingKey: "",
      size: 2,
      isRoleModal: false,
      isMemberModal: false,
      isDeleteModal: false,
      nowRole: null,
      nowRoleName: "",
      cacheData: [],
      // 新增角色无id   修改角色有id
      addRoleState: {
        id: "",
        name: "",
        enableIf: "",
        memo: ""
      }
    };
  },
  methods: {
    onSearch () {
      this.getRoleList(this.params)
    },
    onNewRole () {
      this.isRoleModal = true;
    },
    onAdd (role) {
      this.nowRole = role.id;
      this.nowRoleName = role.name;
      this.isMemberModal = true;
    },
    onDelete (id) {
      this.nowRole = id;
    },
    onDetail (role) {
      this.$router.push({
        path: 'characterDetails',
        query: { role: role }
      });
    },
    onCancel (data) {
      if (data.modal == "添加人员") {
        if (data.success == "ok") {
          let params = {
            roleId: this.nowRole, // this.nowRole
            userIds: data.data.memberList.toString(),
            status: 0
          }
          addMemeber(params).then(res => {
            if(res.data.code == 200) {
              console.log(res.data.data);
            }
          })
        }
        this.isMemberModal = false;
      } else if (data.modal == "新建角色") {
        if (data.success == "ok") {
          this.addRoleState.enableIf = data.data.status;
          this.addRoleState.name = data.data.name;
          this.addRoleState.memo = data.data.note;
          this.addRole(this.addRoleState);
        }
        this.isRoleModal = false;
      }
    },

    // 可编辑行表格
    handleChange (value, key, column) {
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.id)[0];
      if (target) {
        target[column] = value;
        this.dataSource = newData;
      }
    },
    edit (key) {
      this.nowRole = key;
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.id)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.dataSource = newData;
      }
    },
    save (key) {
      const newData = [...this.dataSource];
      this.cacheData = this.dataSource.map(item => ({ ...item }));
      const newCacheData = [...this.cacheData];
      const target = newData.filter(item => key === item.id)[0];
      const targetCache = newCacheData.filter(item => key === item.id)[0];
      if (target && targetCache) {
        delete target.editable;
        this.dataSource = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = "";
      this.addRoleState.id = key;
      this.addRoleState.enableIf = target.enableIf;
      this.addRoleState.memo = target.memo;
      this.addRoleState.name = target.name;
      this.addRole(this.addRoleState);
    },
    cancel (key) {
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.id)[0];
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.filter(item => key === item.id)[0]
        );
        delete target.editable;
        this.dataSource = newData;
      }
    },
    onConfirmDelete () {
      this.dataSource = this.dataSource.filter(val => val.id != this.nowRole);
      deleteRole({ id: this.nowRole }).then(res => {
        if (res.data.code == 200) {
          this.getRoleList();
        }
      })
    },
    /**
     * @description: 分页
     * @param {*} page
     * @param {*} pageSize
     * @return {*}
     */
    onPageChange (page, pageSize) {
      this.params.page = page
      this.params.pageSize = pageSize
    },
    onSizeChange (current, size) {
      this.params.page = 1
      this.params.pageSize = size
    },
    /**
     * @description: 接口
     * @param {*}
     * @return {*}
     */
    getRoleList () {
      let { roleName, page, pageSize } = this.params;
      let params = {
        name: roleName, pageNum: page, pageSize
      }
      roleList(params).then(res => {
        if (res.data.code == 200) {
          const data = res.data.data;
          this.total = data.totalElements;
          this.dataSource = data.content;
          for (var i of this.dataSource) {
            i.updateTime=transferDate(i.updateTime, 2)
          }
        }
      })
    },
    addRole (params) {
      updateRole(params).then(res => {
        if (res.data.code == 200) {
          this.addRoleState.id = "";
          this.getRoleList();
        } else if (res.data.code == 400) {
          console.log(res.data.msg);
        }
      })
    }

  },
  mounted () {
    this.getRoleList()
  }
};
</script>

<style scoped lang="less">
.role-management {
  background: #fff;
  padding: 20px 60px;
}
.roles-table {
  margin-top: 20px;
}
</style>
